<template>
  <div class="user">
    <!-- 顶部登录显示区域 -->
    <van-row @click="showLogin">
      <van-col span="6">
        <img
          :src="avatarSrc"
          alt="头像"
        >
      </van-col>
      <van-col span="14">{{nickName}}</van-col>
      <van-col
        span="4"
        @click="logOut"
      >
        <van-icon :name="logIcon" />
      </van-col>
    </van-row>
    <!-- 其它用户功能区域 -->
    <van-grid
      :column-num="3"
      square
    >
      <van-grid-item
        v-for="(item,index) in incomingFunc"
        :key="index"
        :text="item"
        :icon="incomingIcon[index]"
        @click="handleIncomingFunc"
      />
    </van-grid>
    <!-- 登录模态框 -->
    <section
      class="login_wrapper"
      v-if="isShow"
    >
      <div
        class="login_modal"
        @click="closeLogin"
      >111</div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="loginParams.username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="loginParams.pwd"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <div style="margin: 16px;">
          <van-button
            round
            block
            type="info"
            native-type="submit"
          >登录</van-button>
        </div>
      </van-form>
    </section>

  </div>
</template>

<script>
//别忘了是按需导出的，需要{}
import { Login } from "@/request/api";
export default {
  data() {
    return {
      avatarSrc: require("@/assets/avatar.png"),
      nickName: "点击登录",
      //登录表单双向绑定的对象
      loginParams: { username: "", pwd: "" },
      //控制模态框模块的显示
      isShow: false,
      //右侧登录图标
      logIcon: "arrow",
      //其它用户功能
      incomingFunc: [
        "我的订单",
        "优惠券",
        "礼品卡",
        "我的收藏",
        "我的足迹",
        "会员福利",
        "我的收藏",
        "我的足迹",
        "会员福利",
      ],
      incomingIcon: [
        "label-o",
        "bill-o",
        "debit-pay",
        "star-o",
        "location-o",
        "goods-collect-o",
        "star-o",
        "location-o",
        "goods-collect-o",
      ],
    };
  },
  computed: {
    //右侧登录图标，用计算属性怎么还要刷新一次才改变
    // logIcon() {
    //   let token = localStorage.getItem("token");
    //   if (token) {
    //     return "cross";
    //   } else {
    //     return "arrow";
    //   }
    // },
  },
  created() {
    //每次进入user页面，就判断有没有token。有就获取userInfo登录。
    let token = localStorage.getItem("token");
    if (token) {
      let userInfo = localStorage.getItem("userInfo");
      let objUserInfo = JSON.parse(userInfo);
      this.avatarSrc = objUserInfo.avatar;
      this.nickName = objUserInfo.username;
      this.logIcon = "cross";
    }
  },
  methods: {
    //提交表单
    async onSubmit() {
      let _this = this;
      const res = await Login(_this.loginParams).catch((err) => err);
      // console.log(res);
      if (res.errno !== 0) {
        return this.$toast.fail("登陆失败！");
      }
      this.$toast.success("登陆成功！");
      let { token, userInfo } = res.data;
      //webstorage只能存储字符串，不会报错但只存了字符串：[object Object]
      //可以将对象JSON.stringify() 编码后存储
      let strUserInfo = JSON.stringify(userInfo);
      localStorage.setItem("token", token);
      localStorage.setItem("userInfo", strUserInfo);
      this.avatarSrc = userInfo.avatar;
      this.nickName = userInfo.username;
      this.logIcon = "cross";
      //登陆成功，关闭登录框
      this.closeLogin();
    },
    //点击登录
    showLogin() {
      let token = localStorage.getItem("token");
      if (!token) {
        return (this.isShow = true);
      }
    },
    //点击背景层，关闭模态框表单
    closeLogin() {
      this.isShow = false;
    },
    //点击退出
    async logOut() {
      let token = localStorage.getItem("token");
      if (token) {
        let confirmRes = await this.$dialog
          .confirm({
            title: "退出登录",
            message: "您是否想要退出当前账号？",
          })
          .catch((err) => err);
        // console.log(confirmRes);
        if (confirmRes == "confirm") {
          localStorage.removeItem("token");
          localStorage.removeItem("userInfo");
          //重新渲染页面，否则都不会变。
          this.$toast.success("退出登录！");
          this.reload();
        }
      }
    },
    //其他功能点击
    handleIncomingFunc() {
      this.$toast("该功能尚未开放");
    },
  },
  //注入重新渲染页面的方法
  inject: ["reload"],
};
</script>

<style lang='less' scoped>
.van-row {
  background-color: #333;
  color: #fff;
  padding: 0.2rem 4%;
  line-height: 0.8rem;
  .van-col {
    img {
      width: 0.8rem;
      border-radius: 50%;
    }
    &:last-child {
      text-align: right;
    }
  }
}
.login_wrapper {
  // 让最外层充满屏幕，让背景层元素也充满
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  //盖住tabbar组件
  z-index: 2;
  .login_modal {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .van-form {
    position: absolute;
    width: 90%;
    background-color: #fff;
    //居中
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>